package cn.lili.modules.wallet.serviceimpl;

import cn.hutool.core.date.DateTime;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.vo.GradeVO;
import cn.lili.modules.member.mapper.GradeMapper;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.message.entity.dos.RollMessage;
import cn.lili.modules.message.mapper.RollMessageMapper;
import cn.lili.modules.order.order.entity.enums.PayStatusEnum;
import cn.lili.modules.order.trade.entity.vo.RechargeQueryVO;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.entity.dos.WalletDetail;
import cn.lili.modules.wallet.entity.dos.WalletLogDetail;
import cn.lili.modules.wallet.entity.dto.MemberWalletUpdateDTO;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.vo.RechargeVO;
import cn.lili.modules.wallet.mapper.RechargeMapper;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.RechargeService;
import cn.lili.modules.whitebar.mapper.RateSettingMapper;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Time;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预存款业务层实现
 *
 * @author pikachu
 * @since 2020-02-25 14:10:16
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RechargeServiceImpl extends ServiceImpl<RechargeMapper, Recharge> implements RechargeService {

	/**
	 * 会员预存款
	 */
	@Autowired
	private MemberWalletService memberWalletService;
	// 费率
	@Autowired
	private RateSettingMapper rateSettingMapper;

	@Autowired
	private EextensionService eextensionService;

	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private GradeMapper gradeMapper;

	@Autowired
	private RechargeMapper rechargeMapper;

	@Autowired
	private RollMessageMapper rollMessageMapper;

	@Autowired
	private MemberService memberService;

	@Autowired
	private RegionService regionService;

	@Override
	public Recharge recharge(Double price, Double vipPrice, Double hbprice, String owner, String rechargeType,
			String orderSn) {
		// 获取当前登录的会员
		AuthUser authUser = UserContext.getCurrentUser();
		// 构建sn
		String sn = "Y" + SnowFlake.getId();
		Double yibei = 0D;
		if (null != hbprice) {
			yibei = hbprice;
		} else {
			// 查询充值费率
			// RateSettingVO rateSettingVO =
			// rateSettingMapper.findByPartner(authUser.getId());
			GradeVO gradeVO = gradeMapper.findByGradeVO(authUser.getId());
			// 整合充值订单数据
			// 10----11.6
			// 200---256
			yibei = CurrencyUtil.div(price, gradeVO != null ? gradeVO.getRechargeRule() : 1);
			// if (price.compareTo(new Double("10")) == 0) {
			// yibei = new Double("11.6");
			// } else if (price.compareTo(new Double("200")) == 0) {
			// yibei = new Double("256");
			// }
		}
		Recharge recharge = new Recharge(sn, authUser.getId(), authUser.getUsername(), price, rechargeType, yibei,
				owner, vipPrice, orderSn);
		// 添加预存款充值账单
		this.save(recharge);
		// 返回预存款
		return recharge;
	}

	// 合伙人充值
	@Override
	public Recharge rechargePartner(Double rechargeMoney, Double price, String type, String owner, String memberId,
			String memberName) {
		// 获取当前登录的会员
		AuthUser authUser = UserContext.getCurrentUser();
		if (authUser != null) {
			memberId = authUser.getId();
			memberName = authUser.getUsername();
		}
		// 构建sn
		String sn = "Y" + SnowFlake.getId();
		Recharge recharge = new Recharge(sn, memberId, memberName, price, type, null, owner, rechargeMoney, null);
		// 添加预存款充值账单
		recharge.setPayTime(new Date());
		this.save(recharge);

		// 返回预存款
		return recharge;
	}

	@Override
	public IPage<RechargeVO> rechargePage(PageVO page, RechargeQueryVO rechargeQueryVO) {
		// 构建查询条件
		QueryWrapper<RechargeVO> queryWrapper = new QueryWrapper<>();
		// 会员名称
		queryWrapper.like(!StringUtils.isEmpty(rechargeQueryVO.getMemberName()), "r.member_name",
				rechargeQueryVO.getMemberName());
		// 会员手机号
		queryWrapper.like(!StringUtils.isEmpty(rechargeQueryVO.getMobile()), "m.mobile", rechargeQueryVO.getMobile());
		// 充值订单号
		queryWrapper.eq(!StringUtils.isEmpty(rechargeQueryVO.getRechargeSn()), "r.recharge_sn",
				rechargeQueryVO.getRechargeSn());
		// 会员id
		queryWrapper.eq(!StringUtils.isEmpty(rechargeQueryVO.getMemberId()), "r.member_id",
				rechargeQueryVO.getMemberId());
		// 支付时间 开始时间和结束时间
		if (!StringUtils.isEmpty(rechargeQueryVO.getStartDate())
				&& !StringUtils.isEmpty(rechargeQueryVO.getEndDate())) {
			// Date start =
			// cn.hutool.core.date.DateUtil.parse(rechargeQueryVO.getStartDate());
			// Date end = cn.hutool.core.date.DateUtil.parse(rechargeQueryVO.getEndDate());
			queryWrapper.between("DATE_FORMAT(r.pay_time,'%Y-%m-%d')", rechargeQueryVO.getStartDate(),
					rechargeQueryVO.getEndDate());
		}
		queryWrapper.eq("r.pay_status", "PAID");
		queryWrapper.orderByDesc("r.create_time");
		// 查询返回数据
		return this.rechargeMapper.findList(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public void paySuccess(String sn, String receivableNo, String paymentMethod) {
		// 根据sn获取支付账单
		Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn));
		// 如果支付账单不为空则进行一下逻辑
		if (recharge != null && !recharge.getPayStatus().equals(PayStatusEnum.PAID.name())) {
			// 将此账单支付状态更改为已支付
			recharge.setPayStatus(PayStatusEnum.PAID.name());
			recharge.setReceivableNo(receivableNo);
			recharge.setPayTime(new DateTime());
			recharge.setRechargeWay(paymentMethod);
			// 执行保存操作
			this.updateById(recharge);
			if (!"5".equals(recharge.getRechargeType()) && !"3".equals(recharge.getRechargeType())
					&& !"2".equals(recharge.getRechargeType())) {
				// 增加预存款余额
//				memberWalletService.increase(
//						new MemberWalletUpdateDTO(recharge.getYiBei(), recharge.getMemberId(),
//								"会员余额充值，充值单号为：" + recharge.getRechargeSn(),
//								DepositServiceTypeEnum.WALLET_RECHARGE.name(), recharge.getOwner()),
//						new WalletLogDetail(null, null, "0", recharge.getRechargeSn(), "1", "1", recharge.getMemberId(),
//								recharge.getMemberName(), null, null, null, recharge.getYiBei()));
				memberWalletService.updateWallet(recharge);
			}
		}
	}

	@Override
	public Recharge getRecharge(String sn) {
		Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn));
		if (recharge != null) {
			return recharge;
		}
		throw new ServiceException(ResultCode.ORDER_NOT_EXIST);
	}

	@Override
	public void rechargeOrderCancel(String sn) {
		Recharge recharge = this.getOne(new QueryWrapper<Recharge>().eq("recharge_sn", sn));
		if (recharge != null) {
			recharge.setPayStatus(PayStatusEnum.CANCEL.name());
			this.updateById(recharge);
		}
	}

	public IPage<Map> getRechargeFowPage(RechargeQueryVO recharge, PageVO page) {
		QueryWrapper<RechargeQueryVO> queryWrapper = Wrappers.query();
		// 流水号
		if (StringUtils.isNotEmpty(recharge.getLocation())) {
			List list = regionService.getItemAdCod(recharge.getLocation());
			queryWrapper.in(list.size() > 0, "lm.location", list);
		}
		queryWrapper.eq(StringUtils.isNotEmpty(recharge.getRechargeSn()), "recharge_sn", recharge.getRechargeSn());
		queryWrapper.eq(StringUtils.isNotEmpty(recharge.getMobile()), "lm.mobile", recharge.getMobile());
		queryWrapper.eq(StringUtils.isNotEmpty(recharge.getLevel()), "lmc.level", recharge.getLevel());
		if (StringUtils.isNotEmpty(recharge.getRoleName())) {
			UserEnums userEnums = UserEnums.valueOf(recharge.getRoleName());
			queryWrapper.eq(userEnums != null && StringUtils.isNotEmpty(userEnums.getRole()), "lro.name",
					userEnums.getRole());
		}
		queryWrapper.between(
				StringUtils.isNotEmpty(recharge.getStartDate()) && StringUtils.isNotEmpty(recharge.getEndDate()),
				"lr.pay_time", recharge.getStartDate(), recharge.getEndDate());

		queryWrapper.eq("lr.pay_status", "PAID");
		queryWrapper.eq("lr.recharge_way", "WECHAT");
		queryWrapper.orderByDesc("lr.pay_time");
		queryWrapper.groupBy("lr.recharge_sn");
		IPage<Map> p = this.baseMapper.getRechargeFowPage(PageUtil.initPage(page), queryWrapper);
		for (Map r : p.getRecords()) {
			r.put("locationName", regionService.getItemAdCodOrName(r.get("location").toString()));
		}
		return p;
	}

	@Override
	public Double getByPageSum(QueryWrapper<Recharge> queryWrapper) {
		return baseMapper.getByPageSum(queryWrapper);
	}

}